import { LinRouter, disableLoading } from 'lin-mizar';
import { groupRequired } from '../../middleware/jwt';
import {
  AddFlowValidator,
  EditFlowValidator,
  DeleteFlowValidator,
} from '../../validator/flow';
import { FlowDao } from '../../dao/flow';
import { logger } from '../../middleware/logger';
import { FlowService } from '../../service/flow';


const flowApi = new LinRouter({
  prefix: '/v1/flow',
});

flowApi.linPost(
  'addFlow',
  '/',
  {
    permission: '添加最新期刊内容',
    module: '最新期刊管理',
    mount: true
  },
  // logger({ template: '新增了最新期刊内容' }),
  groupRequired,
  async (ctx) => {
    const v = await new AddFlowValidator().validate(ctx);
    await FlowDao.createFlow(v);
    ctx.success({
      msg: '期刊内容编辑成功'
    })
  }
)


flowApi.linPut(
  'editFlow',
  '/:id',
  {
    permission: '编辑最新期刊内容',
    module: '最新期刊管理',
    mount: true
  },
  // logger({ template: '新增了最新期刊内容' }),
  groupRequired,
  async (ctx) => {
    const v = await new EditFlowValidator().validate(ctx);
    const id = v.get('path.id');
    const index = v.get('body.index')
    const type = v.get('body.type')
    const art_id = v.get('body.art_id')
    const status = v.get('body.status')
    await FlowDao.editFlow(id, index, type, art_id, status);
    ctx.success({
      msg: '最新期刊内容编辑成功'
    })
  }
)


flowApi.linGet(
  'getFlowList',
  '/',
  {
    permission: '查询最新期刊列表',
    module: '最新期刊管理',
    mount: true
  },
  // logger({ template: '新增了最新期刊内容' }),
  groupRequired,
  async (ctx) => {
    const flowList = await FlowService.getFlowList();
    ctx.json(flowList);
  }
)

/**
 * 删除
 */
flowApi.linDelete(
  'deleteFlow',
  '/:id',
  {
    permission: '删除最新期刊内容',
    module: '最新期刊管理',
    mount: true
  },
  logger({ template: '{user.username}删除了最新期刊内容' }),
  groupRequired,
  async ctx => {
    const v = await new DeleteFlowValidator().validate(ctx);
    const id = v.get('path.id');
    await FlowDao.deleteFlow(id);
    ctx.success({
      msg: '最新期刊内容删除成功'
    })
  })

module.exports = { flowApi, [disableLoading]: false };
